package ar.uba.fi.taller2.jh.B34tree;

import java.io.BufferedWriter;
import java.io.IOException;
import java.util.*;

import ar.uba.fi.taller2.jh.BBasicTree.*;
import ar.uba.fi.taller2.jh.Tree.*;

/*****************************************************************************
 * <p>Title: CMSC420 </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2004</p>
 *
 * <p>Company: </p>
 *
 * @author Sebastian rivas
 * @version 1.0
 * 
 ****************************************************************************/

public class B34LeafNode extends BBasicLeafNode {
  
  /****************************************************************************
   * CONSTRUCTOR
   *
   * @param comp Comparator
   * @param n_recs int
   ***************************************************************************/

  public B34LeafNode(Comparator comp,int n_recs, boolean _isRoot, Tree _tree) {
	super(comp, n_recs, _isRoot, _tree);
  }

  /****************************************************************************
   * CONSTRUCTOR
   *
   * @param o BSLeafNode
   ***************************************************************************/

  public B34LeafNode(B34LeafNode o) {
	super(o);
  }

  public int minSize() {
		  return (int)Math.floor(getNum_records()/2);
  }
  
  public Node splitAt(int pos) {
	  
	  int newSize = this.size()-pos-1;
	  boolean newRoot = newSize>this.num_records;
	  
	  B34LeafNode newNode = new B34LeafNode(comparator, this.num_records, newRoot, this.tree);
	  for(int i=pos+1; i<this.size(); i++) {
		   newNode.copyRecord(i-pos-1, this.records[i]);
	  }
	  newNode.rsize = newSize;
	  this.rsize = pos;
	  
	  if(this.isRoot) {
		  this.id = this.tree.getNextNodeId();
		  this.tree.getDisk().storeBlock(this.id.toString());
	  }
	  
	  this.isRoot = false;
	  
	  return newNode;
  }

/**
 * @return the num_records
 */
public int getNum_records() {
	return this.isRoot? num_records*3 : num_records;
}

public Node makeRoot() {
	
	B34LeafNode auxNode = new B34LeafNode(comparator, this.num_records, true, this.tree);
	for(int i=0; i<this.size(); i++) {
		auxNode.append(null, this.records[i].getKey());
	}
	this.tree.getDisk().releaseBlock(this.id);
	return auxNode;
}

}